package com.hymanting.blog.application;

import com.hymanting.blog.domain.article.Article;
import com.hymanting.blog.domain.article.ArticleRepository;
import org.springframework.data.domain.Example;

import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @Author hxchen
 * @Date 2021/6/20
 */
@Named
@Transactional
public class ArticleApplicationService {

    @Inject
    private ArticleRepository repository;

    public Article findArticleByArticleId(Integer articleId) {
        return repository.findById(articleId).orElse(null);
    }

    public List<Article> findPagedArticlesByAuthorId(String authorId) {
        return null;
    }

    public List<Article> getPagedArticles(Integer status) {
        List<Article> articles = new ArrayList<>();
        if (status != null) {
            Article article = new Article();
            article.setStatus(status);
            Example<Article> example = Example.of(article);
            articles = repository.findAll(example);
        } else {
            articles = repository.findAll();
        }
        articles.sort((c1, c2)-> c2.getCreateTime().compareTo(c1.getCreateTime()));
        return articles;
    }

    public boolean createArticle(Article article) {
        return repository.save(article) != null ? true : false;
    }
}
